package com.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author wangfengchen
 */
@Slf4j
@RestController
public class TestController {

  @Autowired
  private ResourceLoader resourceLoader;


  @GetMapping("/test")
  public String test(@RequestParam String b, @RequestParam String c, @RequestParam String a) {
    return b + " " + c + " " + a;
  }

  @PostMapping("/test2")
  public String test2(@RequestParam String b, @RequestParam String c, @RequestParam String a) {
    return b + " " + c + " " + a;
  }

  @GetMapping("/cloudFlare")
  public String ip(HttpServletRequest request) {
//        String ip1 = IpUtil.getIpAddr(request);
//        String ip2 = request.getHeader("X-Forwarded-For");
    String ip = request.getHeader("CF-Connecting-IP");
    String country = request.getHeader("CF-IPCountry");
    String city = request.getHeader("CF-IPCity");
    String continent = request.getHeader("CF-IPContinent");
    // 访问者的经度
    String longitude = request.getHeader("CF-IPLongitude");
    // 访问者的纬度
    String latitude = request.getHeader("CF-IPLatitude");
    String result = "ip = %s，country = %s，city = %s，continent = %s，longitude = %s，latitude = %s";
    return String.format(result, ip, country, city, continent, longitude, latitude);
  }

  /**
   * 返回图片
   *
   * @return
   */
  @GetMapping("/getImage")
  public ResponseEntity<Resource> getImage() {
    // 图片位于src/main/resources/static/image/目录下
    Resource image = resourceLoader.getResource("classpath:/static/image/3.jpg");
    return ResponseEntity.ok()
        .contentType(MediaType.IMAGE_JPEG)
        .body(image);
  }

  @GetMapping("/")
  public String test() {
    return "hello world";
  }


}
